/*
 * @(#)SocketServer.java
 *
 */

package diablo3.socket;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * description
 * 
 * @author huangyixiang
 * @version 2012-12-7
 */
public class SocketServer {
	
	private static final Log LOG = LogFactory.getLog(SocketServer.class);
	private static final int PORT = 80;
	private static Dispatcher dispatcher = new Dispatcher();

	public static void main(String[] args) {
		SocketServer ss = new SocketServer();
		try {
			ss.server();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 服务器端响应请求
	 * 
	 * @throws Exception
	 */
	public void server() throws Exception {

		// 0.建立服务器端的server的socket
		ServerSocket ss = new ServerSocket(80);

		while (true) {
			Socket server = null;
			try{
				// 1.打开socket连接
				// 等待客户端的请求
				LOG.info("监听" +  PORT + "端口开始");
				server = ss.accept();
				LOG.info("线程" + Thread.currentThread().getName() + "启动");

				// 2.打开socket的流信息，准备下面的操作
				InputStream is = server.getInputStream();
				
				/*InputStreamReader reader = new InputStreamReader(is);
				BufferedReader bd = new BufferedReader(reader);
				String t = null;

				while ((t = bd.readLine()) != null) {
					LOG.info(t);
					if(Util.isBlank(t)){
						break;
					}
					// parser(t);//解析每一句的方法
				}
				is.close();*/
				
				SocketRequest socketRequest = new SocketRequest(is);
				socketRequest.ReadData();
				String httpContent = socketRequest.getRequest().toString();
				RequestParser requestParser = new RequestParser();
				Request request = requestParser.parser(httpContent);
				
				//doRequest
				dispatcher.dispatch(request.getRequestURI());
				LOG.info(request);
			}
			catch(Exception e){
				LOG.error(e.getMessage(),e);
			}
			finally{
				if(server != null)server.close();
			}
			
			LOG.info("请求结束");
		}

	}

}
